import { useEffect, useState } from 'react';
import { connect, history } from 'umi';
import { Table, Modal, Form, Input, Button, TreeSelect, Skeleton, message } from 'antd';
import styles from './style.less'
import TextButton from '@/components/TextButton'
import {
} from '@ant-design/icons';
import { deleteEnterpriseDepartment, saveEnterpriseDepartment } from '@/services/enterprise'
const FormItem = Form.Item;


const DepartmentManage = (props) => {

    const {
        dispatch,
        enterpriseId,
        departmentList,
        loadinigDepartment,
        changeToTab
    } = props;
    const baseColumns = [{
        title: '部门名称',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '成员人数',
        dataIndex: 'userCnt',
        key: 'userCnt',
        align: "center",
        render: (text, record) => (<a onClick={() => {
            changeToTab("user", record)
        }}>{record.userCnt || 0} </a>)
    }]

    const actionColumns = [{
        title: '操作',
        dataIndex: 'id',
        key: 'action',
        render: (text, record) => (<div className={styles.actionClass}>
            <TextButton type="primary" onClick={() => {
                showSaveDepartmentModal(record, "add")
            }}>新增</TextButton>

            {record.level != 0 &&
                <TextButton onClick={() => {
                    showSaveDepartmentModal(record, "update")
                }}>修改</TextButton>}
            {record.level != 0 && <TextButton type="danger" onClick={() => {
                deleteDepartment(record)
            }}>删除</TextButton>}
        </div>)
    }]

    const [departmentSaveModalVisible, setDepartmentSaveModalVisible] = useState(false)
    const [initDepartmentData, setInitDepartmentData] = useState({});
    const [form] = Form.useForm();

    useEffect(() => {
        console.log('getEnterpriseDepartment')
        dispatch({
            type: 'enterprise/getEnterpriseDepartment',
        })
    }, [])

    const deleteDepartment = (department) => {
        Modal.confirm({
            title: '删除部门',
            content: `确认删除部门：${department.name}`,
            okText: '确认',
            cancelText: '取消',
            onOk: (v) => {
                deleteEnterpriseDepartment({
                    id: department.id
                }).then(({ success }) => {
                    if (success) {
                        message.success("删除成功！")
                        setDepartmentSaveModalVisible(false)
                        setInitDepartmentData({})
                        dispatch({
                            type: 'enterprise/getEnterpriseDepartment',
                        })
                    }
                })
                return Promise.resolve()
            }
        });
    }

    const showSaveDepartmentModal = (department, action) => {
        console.log(department)
        if (action === 'add') {
            setInitDepartmentData({
                enterpriseId: department.enterpriseId,
                parentId: department.id
            })

        } else if (action === 'update') {
            setInitDepartmentData({
                ...department
            })
        }
        setDepartmentSaveModalVisible(true)
    }
    const saveDepartment = async () => {
        const values = await form.validateFields();
        console.log(values)
        saveEnterpriseDepartment({
            ...values
        }).then(({ success }) => {
            if (success) {
                dispatch({
                    type: 'enterprise/getEnterpriseDepartment',
                })
                hideDepartmentSaveModal()
            }
        })
    }
    const mapsubDepartment = (item) => (item.subDepartment && item.subDepartment.map(sub => (
        <TreeSelect.TreeNode value={sub.id} title={sub.name} key={sub.id}>
            {mapsubDepartment(sub)}
        </TreeSelect.TreeNode>
    )));
    if (!departmentList) {
        return (<Skeleton></Skeleton>)
    }

    const hideDepartmentSaveModal = async () => {
        await setInitDepartmentData({})
        form.resetFields();
        setDepartmentSaveModalVisible(false)
    }

    const filterColumn = (baseColumns) => {

        return [...baseColumns, ...actionColumns]
    }

    return (
        <div>
            <Table
                loading={loadinigDepartment || !departmentList}
                bordered
                pagination={false}
                size="small"
                rowKey="id"
                columns={filterColumn(baseColumns)}
                dataSource={departmentList}
                childrenColumnName='subDepartment'
                defaultExpandAllRows={true}
            ></Table>
            <Modal
                visible={departmentSaveModalVisible}
                closable
                title={initDepartmentData.id ? "修改部门" : "新增部门"}
                onCancel={() => {
                    hideDepartmentSaveModal()
                }}
                destroyOnClose
                onOk={saveDepartment}
            >
                <Form
                    form={form}
                    initialValues={initDepartmentData}
                >
                    <FormItem
                        label="ID"
                        name="id"
                        hidden={true}
                    >
                    </FormItem>
                    <FormItem
                        label="父级部门"
                        name="parentId"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                    >
                        <TreeSelect
                            placeholder="请选择部门"
                            treeDefaultExpandAll
                            onSelect={(value) => {
                                form.setFieldsValue({
                                    parentId: value
                                })
                            }}>
                            {departmentList && departmentList.map((item) => (
                                <TreeSelect.TreeNode key={item.id} value={item.id} title={item.name}>
                                    {mapsubDepartment(item)}
                                </TreeSelect.TreeNode>
                            ))}
                        </TreeSelect>
                    </FormItem>
                    <FormItem
                        label="企业id"
                        name="enterpriseId"
                        hidden={true}
                    >
                    </FormItem>
                    <FormItem
                        label="部门名称"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: "请填入部门名称",
                            },
                        ]}
                    >
                        <Input
                            placeholder="部门名称"
                        />
                    </FormItem>
                </Form>
            </Modal>
        </div>
    )
}

const mappedToStates = ({ enterprise, loading }) => {
    return {
        departmentUserList: enterprise.enterpriseUser,
        departmentList: Object.keys(enterprise.enterpriseDepartment).length > 0 && [enterprise.enterpriseDepartment],
        loadinigDepartment: loading.effects['enterprise/getEnterpriseDepartment'],
    };
}


export default connect(mappedToStates,)(DepartmentManage);